package org.csu.mypetstore_ssm.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_ssm.domain.Cart;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.csu.mypetstore_ssm.domain.Category;
import org.csu.mypetstore_ssm.domain.Item;
import org.csu.mypetstore_ssm.domain.Product;
import org.csu.mypetstore_ssm.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;

@Controller
//@RequestMapping("/cart")
public class CartController {

    @Autowired
    HttpSession httpSession;

    Cart cart;
    @Autowired
    CatalogService catalogService;

    @GetMapping("/view")
    public String view() {
        return "cart/cart";
    }

    //打开购物车界面
    @GetMapping("/cart")
    public void cart(@RequestParam(value = "ItemId", required = false) String itemId, HttpServletResponse response) throws IOException {
        String workingItemId = itemId;

        if (cart == null) {
            cart = new Cart();
        }
        if(workingItemId != null){
            if (cart.containsItemId(workingItemId)) {

                cart.incrementQuantityByItemId(workingItemId);

            } else {

                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item, isInStock);

            }
        }

        httpSession.setAttribute("add",null);
        httpSession.setAttribute("cart",cart);
        response.sendRedirect("/view");
    }

    @GetMapping("/remove")
    public void remove(@RequestParam(value = "itemId", required = false) String Id, HttpServletResponse resp, HttpServletRequest req) throws IOException {
        Cart cart = (Cart) httpSession.getAttribute("cart");

        String workingItemId = Id;
        Item item = cart.removeItemById(workingItemId);

        if (item == null) {
            httpSession.setAttribute("error Msg","Attempted to remove null CartItem from Cart.");
        } else {
            resp.sendRedirect("/view");
        }

    }
}
